<?php
declare (strict_types = 1);

namespace app\admin\controller\cloth;

use think\facade\Request;
use app\common\service\ClothMain as S;
use app\common\model\ClothMain as M;
use app\common\model\ClothType as CT;
use app\common\model\ClothColor as COLOR;
use app\common\model\SupplierMain as SUP;
use app\common\model\CustomerSample as SAMP_M;
use app\common\model\SystemConfig as CONFIG;
use QL\QueryList;

class Main extends  \app\admin\controller\Base
{
	
    protected $middleware = ['AdminCheck','AdminPermission'];
	
	//初始化
	public function initialize(){
		parent::initialize();
		
		$this->assign('controller_title','面料');
	}

    // 列表
    public function index(){
        if (Request::isAjax()) {
            return $this->getJson(M::getList([['uuid','=',$this->uuid]]));
        }

		return $this->fetch('',[
			'type_list'=>CT::getList(['uuid'=>$this->uuid]),
		]);
    }

    // 添加
    public function add(){
        if (Request::isAjax()) {
			//追加uuid
			$data=array_merge(Request::post(),['uuid'=>$this->uuid]);
            return $this->getJson(S::goAdd($data));
        }
        return $this->fetch('edit',[
			'action_up'=>false,
			'type_list'=>CT::listData(['uuid'=>$this->uuid]),
			'supplier'=>SUP::listData(['uuid'=>$this->uuid]),
			'options'=>config_cache_file('options'),
			'component'=>config_cache_file('component'),
		]);
    }

    // 编辑
    public function edit($id){
        if (Request::isAjax()) {
			$post=Request::post();
			$data=array_merge($post,['uuid'=>$this->uuid]);
            $result=S::goEdit($data,['id'=>$id,'uuid'=>$this->uuid]);
			// 如果修改编号，则动态修改颜色表的编号和供货编号
			if(($post['old_number']!=$post['number']) || ($post['old_onumber']!=$post['onumber'])){
				$res=COLOR::update(['number'=>$post['number'],'onumber'=>$post['onumber']],['uuid'=>$this->uuid,'pid'=>$id]);
			}
			return $this->getJson($result);
        }
		
		$model=M::info(['uuid'=>$this->uuid,'id'=>$id]);
		if(!$model) $this->getJson(102);
        
		return $this->fetch('',[
			'action_up'=>true,
			'model' => $model,
			'type_list'=>CT::listData(['uuid'=>$this->uuid]),
			'supplier'=>SUP::listData(['uuid'=>$this->uuid]),
			'options'=>config_cache_file('options'),
			'component'=>config_cache_file('component'),
		]);
    }

    // 状态
    public function status($id){
        return $this->getJson(S::goStatus(Request::post(),['id'=>$id,'uuid'=>$this->uuid]));
    }

    // 删除
    public function remove($id){
        return $this->getJson(S::goRemove(['id'=>$id,'uuid'=>$this->uuid]));
    }

    // 批量删除
    public function batchRemove(){
        return $this->getJson(S::goBatchRemove([
				['id','in',Request::post('ids')],
				['uuid','=',$this->uuid],
			]));
    }

    // 回收站
    public function recycle(){
        if (Request::isAjax()) {
            return $this->getJson(S::goRecycle([['uuid','=',$this->uuid]]));
        }
        return $this->fetch();
    }
	
    // 设置某个值
    public function setValue(){
        if (Request::isAjax()) {
            $type=I('post.type','');
            if($type=='settype'){           //批量设置分类
                return $this->getJson(S::setTypes(Request::post(),$this->uuid)); 
            }else{
                return $this->getJson(S::setFieldValue(Request::post(),['id'=>I('post.id'),'uuid'=>$this->uuid])); 
            }
        }
        return $this->fetch();
    }
	
	// 差价表
	public function cost(){
	    if (Request::isAjax()) {
	        return $this->getJson(M::costList(['status'=>1,'uuid'=>$this->uuid],['sort'=>'asc']));
	    }
		
		return $this->fetch('',[
			'more'=>I('get.more',0),
		]);
	}
	
	//报价表
	public function table(){
		if (Request::isAjax()) {
		    return $this->getJson(M::tableList(['m.status'=>1,'m.wx_isshow'=>1,'m.uuid'=>$this->uuid]));
		}
		
		return $this->fetch('',[
			'more'=>I('get.more',0),
			'today'=>date('Y年m月d日'),
		]);
	}
	
	//VIP报价表
	public function lvip(){
		$zhe=I('get.zhe',0.95);
		
		$model = M::listData(['status'=>1,'uuid'=>$this->uuid],['sort'=>'asc']);
		
		return $this->fetch('',[
			'T'=>$model,
			'zhe'=>$zhe,
			'tpName'=>'',
		]);
	}
	
	// 产品标签打印
	public function label(){
		$id=I('id','');
		$type=I('type','cloth');
		
		if($id==="") $this->error('页面访问有误~！');
		
		if($type === "cloth"){				//打印产品标签
			$id=explode('|',$id);
			$T=M::field('id,title,number,kgm,breadth,square,component,tube,emptykg,side_type')->where([
				['id','in',$id],
				['uuid','=',$this->uuid]
			])->select()->toArray();
		}else if($type === "sample"){		//色卡登记打印
			$card=SAMP_M::where(['id'=>$id,'uuid'=>$this->uuid])->value('card');
			if($card!=''){
				$new_card=$this->replce_number($card,1);		//替换编号对应系统编号
				$card=explode('/', $new_card['card']);
				$T=M::field('id,title,number,kgm,breadth,square,component,tube,emptykg,side_type')->where([
					['number','in',$card],
					['uuid','=',$this->uuid]
				])->select()->toArray();
			}else{
				$this->error('没数据可以生成~！');
			}
		}else{
			$this->error('非法访问~！');
		}
		// 替换
		// $T=$this->replce_number(['data'=>$T,'replce'=>$new_card['replce']],2);
		
		$print=CONFIG::get('info.print');
		
		return $this->fetch('',[
			'T'=>$T,'count'=>count($T),
			'print'=>$data=$print,
			'print_data1'=>json_encode(M::printData($T,$print,'FabricLabel1')),
			'print_data2'=>json_encode(M::printData($T,$print,'FabricLabel2')),
			'print_data3'=>json_encode(M::printData($T,$print,'FabricLabel3')),
		]);
	}
	
	//转化替用产品编号
	private function replce_number($str,$type=1){
		$data=[];
		
		if($type==1){											//转化替代编号,并记录转化过的编号
			$rep_array=[];										//存储替换过的编号
			foreach ($data as $key => $val) {
				$key=strval($key);
				$val=strval($val);
				if(strpos($str,$key)!== false){
					$str=str_replace($key, $val,$str);
					$rep_array[$val]=$key.' ( '.$val.' )';				//位置调换，方便还原
				}
			}
			$str=str_replace(["\r\n", "\r", "\n"],"", $str); 
			return ['card'=>$str,'replce'=>$rep_array];
		}else if($type==2){											//替换编号回产品数组
			if(count($str['replce'])>0){
	    		foreach ($str['data'] as $key=>$val) {
	    			if(array_key_exists($val['number'], $str['replce'])){	//如果存在，就替换编号
	    				$str['data'][$key]['number']=$str['replce'][$val['number']];
	    			}
	    		}
	    	}
			return $str['data'];									//返回替换后的产品数组
		}
	}
	
	// 复制产品
	public function copyCloth(){
		if (Request::isAjax()) {
			$id=I('post.ids','');
			$id=explode('|',$id);
			return $this->getJson(S::copy($id,$this->uuid));
		}else{
			return $this->getJson(404);
		}
	}
	
	//抓取小程序图片-未完善
	protected function zhua(){
		$user_id=6;
		$page=1;
		$index_url="https://api-seka.duojin.xll512.com/v1/tool/cloth/index?user_id=".$user_id."&q=&page=".$page."&expand=category&cat_id=全部&sort=0";
		//$class_url="https://api-seka.duojin.xll512.com/v1/tool/cloth/index?user_id=6&q=&page=1&expand=category&cat_id=90&sort=0";
		
		$list=QueryList::get($index_url)->getHtml();
		$list=json_decode($list,true);
		$list=$list['data']['items'];
		foreach($list as $v){
			$this->getShengHuaInfoImg($v['id'],$user_id);
		}
	}
	
	//抓取产品图片保存本地--未完善
	protected function getShengHuaInfoImg($id,$user_id){
		$down_path="D:\/pw\/seka1\/";
		$suffix='.jpg';
		$info_url="https://api-seka.duojin.xll512.com/v1/tool/cloth/detail?user_id=".$user_id."&id=".$id."&member_id=59381";
		$list=QueryList::get($info_url)->getHtml();
		$list=json_decode($list,true);
		$number=str_replace("#","",$list['data']['outer_id']);
		$down_path.=$number;
		$cover=$list['data']['pic_url'];
		$list=$list['data']['pictures'];
		$details=$list[1];
		array_splice($list,0,2);
		echo $number.'<br/>';
		for($i=0;$i<count($list);$i++){
			$file_name=$number.'_color'.($i+1).$suffix;
			$res=save_web_images2($list[$i],$down_path,$file_name,false);
			//echo $file_name.' : '.$res['msg'].'<br>';
		}
		$res=save_web_images2($cover,$down_path,$number.'_cover'.$suffix,false);
		//echo $number.'_cover'.$suffix.' : '.$res['msg'].'<br>';
		$res=save_web_images2($details,$down_path,$number.'_details'.$suffix,false);
		//echo $number.'_details'.$suffix.' : '.$res['msg'].'<br>';
	}
}
